import _ from 'lodash';
import React, { Fragment } from "react";
import View from "../base/View";
import defaultData from "./data";
import { WeaInput, WeaLocaleProvider, WeaSelect } from "ecCom";
import { detailTypes, OTHER } from "../../../../../constants/form";
import types from "./types";
import classNames from 'classnames';
import './View.less';
const getLabel = WeaLocaleProvider.getLabel;

const { RADIO, CHECKBOX } = detailTypes;

export default class SelectView extends View {

  selectRef = React.createRef();

  state = {
    otherValue: ''
  };

  componentDidMount() {
    this.setOtherTitle();
  }

  componentWillReceiveProps() {
    //重新渲染other选择项的title
    setTimeout(this.setOtherTitle, 100)
  }

  setOtherTitle = () => {
    const { data: { options, type } } = this.props;

    if (type !== types.CHECKBOX || !this.selectRef.current) return;
    
    const selectDom = this.selectRef.current.refs.wrapper;
    let index = 0;
    let showname = null;

    options.some((opt, i) => {
      if (OTHER === opt.key && _.isString(opt.showname)) {
        index = i;
        showname = opt.showname;
        return;
      }
    });

    // 没有其他选项
    if (showname === null) return;

    const otherLable = selectDom.querySelectorAll('.ant-checkbox-group label')[index];
    const spanDom = otherLable.childNodes[1].childNodes[0];

    spanDom.setAttribute('title', showname);
  }

  formatValue = value => {
    const { otherValue } = this.state;
    const vals = value.split(',');
    const newValue = vals.map(val => ({
      key: val,
      value: OTHER === val ? otherValue : ''
    }));

    return newValue;
  }

  handleOtherValueChange = otherValue => {
    const { value } = this.props;
    const other = value.find(({ key }) => OTHER === key);

    this.setState({ otherValue });

    if (!other) return;

    other.value = otherValue;

    this.props.onChange([...value]);
  }

  getOpts(options) {
    const { otherValue } = this.state;
    return options.map((opt, index) => {
      const newOpt = { ...opt };

      if (OTHER === opt.key && _.isString(opt.showname)) {
        newOpt.showname = (
          <Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@i0ercg@`}>
            {opt.showname}
            <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@qtsrbh@${index}`}
              value={otherValue}
              onChange={this.handleOtherValueChange}
              onFocus={this.selectOtherOpt}
            />
          </Fragment>
        );
      }

      if (!opt.showname) {
        newOpt.showname = getLabel('502263', '选项');
      }
      return newOpt;
    });
  }

  selectOtherOpt = () => {
    const { value, data } = this.props;
    let values = value.map(({ key }) => key);

    if (values.includes(OTHER)) return;

    if (types.CHECKBOX === data.type) {
      values.push(OTHER);
      values = values.join(',');
    } else {
      values = OTHER;
    }

    const newValue = this.formatValue(values);

    this.props.onChange(newValue);
  };

  renderContent(data, value) {
    const { options, type, isVertical } = data;
    const detailtype = type === types.CHECKBOX ? CHECKBOX : RADIO;
    const vals = value.map(({ key, value }) => {
      if (OTHER === key) {
        this.state.otherValue = value;
      }
      return key;
    }).join(',');

    const opts = this.getOpts(options);
    const verticalCls = classNames({
      'wea-edc-select-vertical': !Boolean(isVertical)
    })

    return (
        <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@gx3ri6`}
          className={verticalCls}
          value={vals}
          ref={this.selectRef}
          key={`${detailtype}${isVertical}`} // 用于强制更新组件类型
          options={opts}
          detailtype={detailtype}
          supportCancel
          onChange={this.handleValueChange}
        />
    );
  }

  renderForReadonly(data, value) {
    let options = {};
    const { isVertical } = data;
    const readonlyCls = classNames({
      'read-only-select': !Boolean(isVertical)
    })

    data.options.map(({ key, showname }) => {
      options[key] = showname;
    });
    
    return (
      <ul>
        {value.map(({ key, value }) => (
          <li className={readonlyCls}>{value || options[key]}</li>
        ))}
      </ul>
    )
  }
}

SelectView.defaultProps = {
  data: defaultData,
  value: []
};